<template>
  <div class="base-upload">
    <el-upload
      ref="upload"
      :action="uploadFileUrl"
      :headers="headers"
      :before-upload="validate"
      :show-file-list="false"
      :on-success="handleSuccess"
      v-bind="$attrs"
      v-on="$listeners"
    >
      <slot>
        <el-button
          v-if="!$attrs['list-type'] || $attrs['list-type'] === 'text'"
          icon="el-icon-upload2"
          :disabled="$attrs.disabled"
        >
          {{ buttonText }}
        </el-button>
      </slot>
    </el-upload>
    <div v-if="showTip" class="upload-tips">
      <template v-if="fileType.length"> 支持扩展名: {{ fileType.map(v => `.${v} `).join('') }} </template>
    </div>

    <UploadList
      :show-file-list="$attrs['show-file-list'] || true"
      :disabled="$attrs.disabled"
      :list-type="$attrs.listType"
      :files="$attrs['file-list']"
      @remove="handleRemove"
    />
  </div>
</template>

<script>
import UploadList from './upload-list.vue'

export default {
  name: 'BaseUpload',
  components: {
    UploadList
  },
  props: {
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg', 'xls']
    fileType: {
      type: Array,
      default: () => []
    },
    // 是否显示提示
    showTip: {
      type: Boolean,
      default: true
    },
    buttonText: {
      type: String,
      default: '上传文件'
    },
    onSuccess: {
      type: Function,
      default: () => {}
    },
    // eslint-disable-next-line vue/require-default-prop
    beforeRemove: Function,
    onRemove: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      // uploadFileUrl: process.env.VUE_APP_BASE_API + '/file/upload',
      uploadFileUrl: 'https://jsonplaceholder.typicode.com/posts/',
      headers: {
        Authorization: 'Bearer '
      },
    }
  },
  methods: {
    // 上传前校检格式和大小
    validate(file) {
      let flag = true
      // 校检文件类型
      if (this.fileType.length) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
          this.clearFiles()
          flag = false
        }
      }
      // 校检文件大小
      if (flag && this.fileSize) {
        const isLt = file.size / 1024 / 1024 > this.fileSize
        if (isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
          flag = false
        }
      }
      return flag
    },
    handleSuccess(res, file, fileList) {
      this.$message.success('上传成功')
      this.onSuccess(res, file, fileList)
    },
    handleRemove(file) {
      const doRemove = () => {
        this.abort(file)
        const fileList = this.$attrs['file-list'] || []
        fileList.splice(fileList.indexOf(file), 1)
        this.onRemove(file, fileList)
      }
      if (!this.beforeRemove) {
        doRemove()
      } else if (typeof this.beforeRemove === 'function') {
        const before = this.beforeRemove(file, this.$attrs['file-list'])
        if (before && before.then) {
          before.then(() => {
            doRemove()
          })
        } else if (before !== false) {
          doRemove()
        }
      }
    },
    abort(file) {
      this.$refs.upload.abort(file)
    },
    // 外部调用方法,清空已上传的文件列表
    clearFiles() {
      this.$refs.upload.clearFiles()
    },
    // 外部调用方法,手动上传文件列表
    submit() {
      return this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped lang="scss">
.base-upload {
  width: 100%;
}
::v-deep .el-upload {
  text-align: left;
}
.upload-tips {
  color: #aaaaaa;
}
</style>
